Using List Methods, Slicing, and Nested Lists in Python
Course: Python Training
Topic: Using List Methods, Slicing, and Nested Lists
Course Link: Python Training Course
Demo Registration: Register for a Free Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction
Lists are one of the most important data structures in Python. They allow programmers to store multiple values in a single variable and perform operations such as adding, removing, updating, searching, sorting, and organizing elements.
Python provides built-in list methods for manipulating list contents. List slicing allows you to extract a portion of a list, while nested lists allow you to store lists inside other lists. These features are useful when working with student records, product inventories, marks, matrices, tables, and other structured data.
In this topic, you will learn how to use common list methods, retrieve and modify portions of lists through slicing, and access data stored inside nested lists.
2. Learning Objectives
- Understand the properties and structure of Python lists.
- Use methods such as
append(), extend(), insert(), remove(), and pop().
- Search, count, sort, and reverse list elements.
- Access portions of a list using positive and negative slicing.
- Modify lists through slice assignment.
- Create and access nested lists.
- Update values inside nested lists.
- Apply list methods, slicing, and nested lists to practical programming problems.
3. Understanding Python Lists
A list is an ordered and mutable collection of elements. Lists are written using square brackets [], and individual elements are separated by commas.
numbers = [10, 20, 30, 40, 50]
names = ["Amit", "Priya", "Rahul"]
mixed = [10, "Python", 3.5, True]
empty_list = []
print(numbers)
print(names)
print(mixed)
print(empty_list)
Output:
[10, 20, 30, 40, 50]
['Amit', 'Priya', 'Rahul']
[10, 'Python', 3.5, True]
[]
3.1 Important Characteristics of Lists
| Characteristic |
Explanation |
| Ordered |
Elements maintain their position in the list. |
| Mutable |
Elements can be added, removed, or modified. |
| Indexed |
Elements can be accessed using indexes starting at zero. |
| Duplicates allowed |
The same value can appear more than once. |
| Mixed data types |
A list can contain numbers, strings, Boolean values, and other objects. |
| Nesting supported |
A list can contain other lists. |
3.2 Accessing List Elements
fruits = ["Apple", "Banana", "Mango", "Orange"]
print(fruits[0])
print(fruits[2])
print(fruits[-1])
print(fruits[-2])
Output:
Apple
Mango
Orange
Mango
Positive indexes count from the beginning, starting at 0. Negative indexes count backward from the end, starting at -1.
4. What Are List Methods?
List methods are built-in operations associated with Python list objects. They help manipulate or inspect list elements without requiring you to implement every operation manually.
A list method is called using the following syntax:
list_name.method_name(arguments)
For example:
numbers = [10, 20, 30]
numbers.append(40)
print(numbers)
Output:
[10, 20, 30, 40]
The append() method adds one element to the end of the existing list.
5. Adding Elements to a List
5.1 The append() Method
The append() method adds a single object to the end of a list. If the object is another list, that entire list becomes one element.
languages = ["Python", "Java"]
languages.append("JavaScript")
print(languages)
languages.append(["C", "C++"])
print(languages)
Output:
['Python', 'Java', 'JavaScript']
['Python', 'Java', 'JavaScript', ['C', 'C++']]
Use case: Adding a new student name, product, task, or transaction to a collection.
5.2 The extend() Method
The extend() method adds each element from an iterable to the end of a list. Unlike append(), it does not add the supplied list as one nested element.
numbers = [1, 2, 3]
numbers.extend([4, 5, 6])
print(numbers)
Output:
[1, 2, 3, 4, 5, 6]
Use extend() when you want to combine the elements of two lists into one list.
5.3 The insert() Method
The insert() method adds an element at a specified index. Existing elements at that position and later positions shift to the right.
colors = ["Red", "Blue", "Green"]
colors.insert(1, "Yellow")
print(colors)
Output:
['Red', 'Yellow', 'Blue', 'Green']
The first argument specifies the insertion index, and the second argument specifies the value to insert.
5.4 append(), extend(), and insert() Compared
| Method |
Purpose |
Example |
Result |
append() |
Adds one object at the end. |
a.append([3, 4]) |
[1, 2, [3, 4]] |
extend() |
Adds each item from an iterable. |
a.extend([3, 4]) |
[1, 2, 3, 4] |
insert() |
Adds one object at a given position. |
a.insert(1, 9) |
[1, 9, 2] |
Each result in the table assumes the starting list is [1, 2].
6. Removing Elements from a List
6.1 The remove() Method
The remove() method removes the first occurrence of a specified value. If the value is not present, Python raises a ValueError.
numbers = [10, 20, 30, 20, 40]
numbers.remove(20)
print(numbers)
Output:
[10, 30, 20, 40]
Only the first occurrence of 20 is removed.
6.2 The pop() Method
The pop() method removes and returns an element. If you omit the index, it removes the last element.
fruits = ["Apple", "Banana", "Mango", "Orange"]
removed_fruit = fruits.pop()
print(removed_fruit)
print(fruits)
second_fruit = fruits.pop(1)
print(second_fruit)
print(fruits)
Output:
Orange
['Apple', 'Banana', 'Mango']
Banana
['Apple', 'Mango']
Use pop() when you need both to remove an element and to use its value afterward.
6.3 The clear() Method
The clear() method removes all elements from the list but leaves the list object available for future use.
tasks = ["Study", "Practice", "Revise"]
tasks.clear()
print(tasks)
Output:
[]
6.4 remove(), pop(), and clear() Compared
| Method |
What it removes |
Returns a removed value? |
remove(value) |
First matching value |
No |
pop(index) |
Element at an index; last by default |
Yes |
clear() |
All elements |
No; returns None |
7. Searching and Counting List Elements
7.1 The index() Method
The index() method returns the index of the first matching value. If the value does not exist in the searched range, Python raises a ValueError.
languages = ["Python", "Java", "C++", "Java"]
print(languages.index("Java"))
print(languages.index("Java", 2))
Output:
1
3
The second argument, 2, tells Python to begin searching from index 2.
7.2 The count() Method
The count() method returns the number of times a value appears in a list.
marks = [80, 90, 80, 70, 80, 95]
print(marks.count(80))
print(marks.count(100))
Output:
3
0
7.3 Using the in Operator
The in operator checks whether a value exists in a list and returns True or False.
courses = ["Python", "SQL", "Power BI"]
print("SQL" in courses)
print("Java" in courses)
Output:
True
False
Use in before calling index() when the value may not exist and you want to avoid an unhandled ValueError.
8. Sorting and Reversing Lists
8.1 The sort() Method
The sort() method sorts a list in place. By default, values are arranged in ascending order.
numbers = [45, 12, 78, 23, 9]
numbers.sort()
print(numbers)
Output:
[9, 12, 23, 45, 78]
To sort in descending order, use reverse=True.
numbers = [45, 12, 78, 23, 9]
numbers.sort(reverse=True)
print(numbers)
Output:
[78, 45, 23, 12, 9]
8.2 The reverse() Method
The reverse() method reverses the current order of the elements. It does not sort the values.
numbers = [30, 10, 40, 20]
numbers.reverse()
print(numbers)
Output:
[20, 40, 10, 30]
8.3 sort() Versus sorted()
numbers = [30, 10, 20]
result = sorted(numbers)
print(result)
print(numbers)
Output:
[10, 20, 30]
[30, 10, 20]
sort() modifies the original list and returns None. The sorted() function creates and returns a new sorted list, leaving the original list unchanged.
8.4 The copy() Method
The copy() method creates a shallow copy of a list.
original = [10, 20, 30]
copied = original.copy()
copied.append(40)
print(original)
print(copied)
Output:
[10, 20, 30]
[10, 20, 30, 40]
A shallow copy creates a new outer list, but nested objects inside it may still be shared.
8.5 Summary of Common List Methods
| Method |
Purpose |
Important detail |
append(x) |
Add one item at the end |
Modifies the original list |
extend(iterable) |
Add items from an iterable |
Extends the existing list |
insert(i, x) |
Insert an item at an index |
Shifts later elements |
remove(x) |
Remove the first matching value |
Raises ValueError if absent |
pop(i) |
Remove and return an item |
Last item is used if index is omitted |
clear() |
Remove all elements |
Leaves an empty list |
index(x) |
Find the first matching index |
Raises ValueError if absent |
count(x) |
Count matching values |
Returns an integer |
sort() |
Sort in place |
Returns None |
reverse() |
Reverse current order |
Does not sort values |
copy() |
Create a shallow copy |
Nested objects may remain shared |
9. Understanding List Slicing
List slicing extracts a portion of a list and returns it as a new list. It is useful for selecting ranges, retrieving the first or last elements, skipping items, and making shallow copies.
The general syntax is:
list_name[start:stop:step]
| Parameter |
Meaning |
start |
Index where the slice begins; included in the result. |
stop |
Index where the slice ends; excluded from the result. |
step |
Number of positions to move between selected elements. |
9.1 Basic Slicing
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4])
print(numbers[:3])
print(numbers[3:])
print(numbers[:])
Output:
[20, 30, 40]
[10, 20, 30]
[40, 50, 60]
[10, 20, 30, 40, 50, 60]
When start is omitted, slicing begins at the start of the list. When stop is omitted, slicing continues to the end. The expression numbers[:] creates a shallow copy of the list.
9.2 Slicing with Negative Indexes
Negative indexes count backward from the end of a list. The index -1 identifies the final element.
letters = ["A", "B", "C", "D", "E", "F"]
print(letters[-3:])
print(letters[:-2])
print(letters[-5:-2])
Output:
['D', 'E', 'F']
['A', 'B', 'C', 'D']
['B', 'C', 'D']
9.3 Slicing with a Step
The step determines how many positions Python moves between selected elements. A positive step moves from left to right, while a negative step moves from right to left.
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[::2])
print(numbers[1::2])
print(numbers[::-1])
print(numbers[7:2:-2])
Output:
[0, 2, 4, 6, 8]
[1, 3, 5, 7, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[7, 5, 3]
A step of zero is invalid and raises a ValueError.
9.4 Updating a List Using Slice Assignment
Slice assignment replaces a section of a list. Unlike ordinary slicing, which creates a new list, slice assignment changes the existing list.
letters = ["a", "b", "c", "d", "e"]
letters[1:3] = ["B", "C"]
print(letters)
letters[2:4] = ["X"]
print(letters)
letters[1:2] = []
print(letters)
Output:
['a', 'B', 'C', 'd', 'e']
['a', 'B', 'X', 'e']
['a', 'X', 'e']
Slice assignment can replace multiple elements with a different number of elements. Assigning an empty list to a slice removes the selected elements.
9.5 Practical Slicing Examples
scores = [65, 72, 88, 91, 76, 84]
first_three = scores[:3]
last_two = scores[-2:]
every_second = scores[::2]
reversed_scores = scores[::-1]
print("First three:", first_three)
print("Last two:", last_two)
print("Every second:", every_second)
print("Reversed:", reversed_scores)
Output:
First three: [65, 72, 88]
Last two: [76, 84]
Every second: [65, 88, 76]
Reversed: [84, 76, 91, 88, 72, 65]
10. Understanding Nested Lists
A nested list is a list that contains one or more lists as elements. Nested lists are useful for representing tables, matrices, grouped records, classroom marks, seating arrangements, and other multidimensional data.
students = [
["Amit", 85],
["Priya", 92],
["Rahul", 78]
]
print(students)
Output:
[['Amit', 85], ['Priya', 92], ['Rahul', 78]]
In this example, each inner list stores a student's name and score.
10.1 Accessing Elements in Nested Lists
Use multiple indexes to access an element inside an inner list. The first index selects the inner list, and the second index selects an element inside that list.
students = [
["Amit", 85],
["Priya", 92],
["Rahul", 78]
]
print(students[0])
print(students[1][0])
print(students[2][1])
Output:
['Amit', 85]
Priya
78
students[1][0] means: select the second inner list, then retrieve its first element.
10.2 Updating Values in Nested Lists
Nested lists are mutable, so you can change elements inside an inner list by using multiple indexes.
students = [
["Amit", 85],
["Priya", 92],
["Rahul", 78]
]
students[2][1] = 88
students[1][0] = "Priya Sharma"
print(students)
Output:
[['Amit', 85], ['Priya Sharma', 92], ['Rahul', 88]]
10.3 Adding and Removing Inner Lists
classroom = [
["Amit", 85],
["Priya", 92]
]
classroom.append(["Rahul", 78])
print(classroom)
classroom.pop(0)
print(classroom)
Output:
[['Amit', 85], ['Priya', 92], ['Rahul', 78]]
[['Priya', 92], ['Rahul', 78]]
Methods such as append() and pop() work on nested lists just as they do on ordinary lists. The method acts on whichever list appears before the dot.
10.4 Slicing Nested Lists
You can slice the outer list to select several inner lists, or slice an inner list to select a portion of its elements.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[:2])
print(matrix[1][1:])
print(matrix[0:3:2])
Output:
[[1, 2, 3], [4, 5, 6]]
[5, 6]
[[1, 2, 3], [7, 8, 9]]
10.5 Iterating Through Nested Lists
Nested loops can be used to visit each value in a nested list.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for value in row:
print(value, end=" ")
print()
Output:
1 2 3
4 5 6
7 8 9
The outer loop processes each row. The inner loop processes the elements in the current row.
10.6 Calculating Row Totals
Nested lists often represent tabular information. You can process each inner list separately to calculate totals.
marks = [
[80, 85, 90],
[70, 75, 80],
[95, 90, 92]
]
for index, row in enumerate(marks, start=1):
total = sum(row)
print("Student", index, "total:", total)
Output:
Student 1 total: 255
Student 2 total: 225
Student 3 total: 277
11. Working with Two-Dimensional Lists
A two-dimensional list is a list of lists that is commonly used to represent rows and columns. Although it can resemble a table or matrix, Python lists do not require every row to have the same length.
matrix = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
]
print("First row:", matrix[0])
print("Second row, third column:", matrix[1][2])
print("Third row, first column:", matrix[2][0])
Output:
First row: [10, 20, 30]
Second row, third column: 60
Third row, first column: 70
11.1 Modifying a Matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
matrix[0][1] = 99
matrix[2].append(10)
print(matrix)
Output:
[[1, 99, 3], [4, 5, 6], [7, 8, 9, 10]]
11.2 Creating Independent Rows Correctly
Be careful when creating a matrix with repeated references to the same inner list.
# Avoid this pattern when independent rows are required
matrix = [[0] * 3] * 2
matrix[0][0] = 9
print(matrix)
Output:
[[9, 0, 0], [9, 0, 0]]
Both outer-list elements refer to the same inner list. Changing one row therefore appears to change both rows.
Create independent rows with a list comprehension instead:
matrix = [[0] * 3 for _ in range(2)]
matrix[0][0] = 9
print(matrix)
Output:
[[9, 0, 0], [0, 0, 0]]
12. Combining List Methods, Slicing, and Nested Lists
Real applications often combine several list operations. The following example manages a list of student records, where each record is itself a list.
students = [
["Amit", 85],
["Priya", 92],
["Rahul", 78],
["Neha", 88]
]
# Add a new student
students.append(["Karan", 81])
# Update Rahul's score
for student in students:
if student[0] == "Rahul":
student[1] = 82
# Display the first three records
print("First three records:", students[:3])
# Find the highest score
highest_score = max(student[1] for student in students)
print("Highest score:", highest_score)
# Sort records by score in descending order
students.sort(key=lambda student: student[1], reverse=True)
print("Sorted records:", students)
Output:
First three records: [['Amit', 85], ['Priya', 92], ['Rahul', 82]]
Highest score: 92
Sorted records: [['Priya', 92], ['Neha', 88], ['Amit', 85], ['Karan', 81], ['Rahul', 82]]
The example demonstrates adding records, updating an inner list, extracting a slice, calculating a maximum, and sorting records using a key function.
13. Common Mistakes and Troubleshooting
| Mistake |
Why it happens |
Correct approach |
| Using an invalid index |
The requested position is outside the list's valid index range. |
Check the list length or use slicing when a shorter result is acceptable. |
Expecting append() to return a new list |
append() modifies the existing list and returns None. |
Call append() separately, then use the modified list. |
Confusing append() with extend() |
One adds a single object; the other adds elements from an iterable. |
Choose the method based on whether a nested element or separate elements are needed. |
Calling remove() for a missing value |
The value does not exist in the list. |
Check with if value in items: before removing. |
Confusing sort() with sorted() |
They have different effects on the original list. |
Use sort() for in-place sorting and sorted() for a new sorted list. |
| Misunderstanding slice boundaries |
The stop index is excluded. |
Remember that items[start:stop] includes start but not stop. |
| Using an invalid slice step |
A step of zero is not permitted. |
Use a nonzero step such as 1, 2, or -1. |
| Incorrect nested indexing |
An index selects the wrong row or element. |
Check each index separately, such as matrix[row][column]. |
| Accidentally sharing inner lists |
Repeated references point to the same nested list. |
Use a list comprehension to create independent rows. |
| Modifying a list while iterating over it |
Removing or inserting elements can cause items to be skipped or processed unexpectedly. |
Iterate over a copy or build a new filtered list. |
13.1 Example: Safely Removing Values
numbers = [10, 20, 30, 20]
if 40 in numbers:
numbers.remove(40)
else:
print("Value not found")
if 20 in numbers:
numbers.remove(20)
print(numbers)
Output:
Value not found
[10, 30, 20]
14. Best Practices for List Operations
- Use meaningful variable names such as
student_scores, product_list, or matrix.
- Use
append() to add one object and extend() to add multiple elements from an iterable.
- Use
pop() when you need the removed value; use remove() when you know the value to remove.
- Use slicing to select ranges without writing unnecessary loops.
- Remember that slicing creates a new outer list, but a slice of a nested list is still a shallow copy.
- Use multiple indexes carefully when reading or updating nested data.
- Use list comprehensions for concise transformations and filtering when they remain readable.
- Use
sorted() if the original order must remain unchanged.
- Avoid using the variable name
list, because it shadows Python's built-in list type.
- Validate input and check whether values exist before using methods that can raise exceptions.
15. Practice Exercises
Exercise 1: Add and Remove Elements
Create a list of five cities. Add a new city, insert another city at index 1, and remove one city by value.
cities = ["Mumbai", "Pune", "Delhi", "Chennai", "Jaipur"]
cities.append("Surat")
cities.insert(1, "Nashik")
cities.remove("Delhi")
print(cities)
Expected output:
['Mumbai', 'Nashik', 'Pune', 'Chennai', 'Jaipur', 'Surat']
Exercise 2: Extract a Slice
Given the list below, print the first four elements, the last three elements, and every second element.
values = [5, 10, 15, 20, 25, 30, 35, 40]
print(values[:4])
print(values[-3:])
print(values[::2])
Expected output:
[5, 10, 15, 20]
[30, 35, 40]
[5, 15, 25, 35]
Exercise 3: Work with Nested Lists
Create a nested list containing three students and their marks. Update one student's marks and display the name and score of the second student.
students = [
["Asha", 75],
["Rohan", 82],
["Meera", 91]
]
students[0][1] = 80
print(students[1][0])
print(students[1][1])
print(students)
Expected output:
Rohan
82
[['Asha', 80], ['Rohan', 82], ['Meera', 91]]
Exercise 4: Sort and Count
Sort a list of numbers in ascending order, count the number of occurrences of a chosen value, and display the reversed list.
numbers = [8, 3, 8, 1, 5, 8, 2]
numbers.sort()
print("Sorted:", numbers)
print("Count of 8:", numbers.count(8))
print("Reversed:", numbers[::-1])
Expected output:
Sorted: [1, 2, 3, 5, 8, 8, 8]
Count of 8: 3
Reversed: [8, 8, 8, 5, 3, 2, 1]
Exercise 5: Mini Project — Student Marks Manager
Build a small program that stores student names and marks in nested lists. The program should allow you to add a student, update marks, show the first few records, and sort students by marks.
students = [
["Amit", 76],
["Priya", 91],
["Rahul", 84]
]
# Add a student
students.append(["Neha", 88])
# Update Rahul's marks
for student in students:
if student[0] == "Rahul":
student[1] = 89
# Show the first two records
print("First two:", students[:2])
# Sort from highest to lowest marks
students.sort(key=lambda student: student[1], reverse=True)
print("Ranked students:")
for student in students:
print(student[0], "-", student[1])
Expected output:
First two: [['Amit', 76], ['Priya', 91]]
Ranked students:
Priya - 91
Rahul - 89
Neha - 88
Amit - 76
16. Interview Questions and Answers
Q1. What is a list in Python?
A list is an ordered, mutable collection that can contain duplicate values and elements of different data types.
Q2. What is the difference between append() and extend()?
append() adds one object to the end of a list, while extend() adds each element from an iterable to the list.
Q3. What is the difference between remove() and pop()?
remove() deletes the first matching value. pop() deletes and returns the element at a specified index, or the last element if no index is supplied.
Q4. What is list slicing?
List slicing extracts a range of elements and returns them as a new list using the syntax list[start:stop:step].
Q5. Is the stop index included in a slice?
No. The start index is included, but the stop index is excluded.
Q6. How can you reverse a list using slicing?
Use my_list[::-1]. This returns a reversed shallow copy without changing the original list.
Q7. What is a nested list?
A nested list is a list containing one or more lists as elements. It can represent grouped data, rows, columns, or matrices.
Q8. How do you access a value in a nested list?
Use multiple indexes. For example, matrix[1][2] accesses the element at index 2 in the inner list at index 1.
Q9. What is the difference between sort() and sorted()?
sort() changes the original list and returns None. sorted() returns a new sorted list and leaves the original list unchanged.
Q10. How do you copy a list?
You can use my_list.copy(), my_list[:], or list(my_list). These create shallow copies, so nested objects may still be shared.
Q11. How can you access the last item in a list?
Use my_list[-1]. The list must contain at least one element or an IndexError will occur.
Q12. Why can multiplying a nested list cause unexpected results?
Expressions such as [[0] * 3] * 2 repeat references to the same inner list. Use a list comprehension when each row needs to be independent.
17. Quick Revision Checklist
append() adds one object at the end.
extend() adds elements from an iterable.
insert() adds an object at a specified index.
remove() removes the first matching value.
pop() removes and returns an element.
clear() empties the list.
index() finds the first matching index.
count() counts occurrences of a value.
sort() sorts the list in place.
reverse() reverses the current order.
copy() creates a shallow copy.
items[start:stop:step] extracts a slice.
items[::-1] returns a reversed shallow copy.
matrix[row][column] accesses a value in a nested list.
- List methods such as
append() and sort() usually modify the existing list and return None.
18. Conclusion
List methods, slicing, and nested lists are essential tools for organizing and manipulating data in Python. List methods help add, remove, search, count, and sort elements. Slicing provides a concise way to retrieve or replace ranges of elements, while nested lists make it possible to represent structured data such as student records and matrices.
Practice these concepts with small programs before combining them into larger applications. Understanding the difference between modifying a list and creating a new list will help you write clearer, safer, and more maintainable Python code.
Additional Learning Resources